import React, { useState, useEffect } from 'react';
import { useHistory } from "react-router-dom";
import http from '../../../model/http';
import code from "../../../model/code";
import './project.less';
import '../../../libs/font/iconfont.css'
import { SearchBar, Toast, Tabs, WingBlank, Drawer,Modal,Stepper, Accordion } from 'antd-mobile';  
import Header from '../../../components/header/Header'

function BillingProject() {
    const history = useHistory();
    const [searchVal, setSearchVal] = useState('')
    const tabs = [
        { title: '项目' ,value:'1'},
        { title: '产品' ,value:'2'},
        { title: '套餐' ,value:'3'},
        { title: '活动' ,value:'4'},
    ]; 
    const [moduleShow, setModuleShow] = useState(false)

    // 上面标签导航的数据
    const [labelData, setLabelData] = useState([{name:'项目',id:0}]) 

    // 分类的数据
    const [typeData,setTypeData] = useState([])
    // 项目的数据
    const [listData, setListData] = useState([])

    // 标签页的状态
    const [tabsStatus, setTabsStatus] = useState('1')

    // 暂存的数据
    const [cartLocalData, setCartLocalData] = useState([])
    const [cartLocalDataID,setCartLocalDataID] = useState([])

    // 套餐的数据
    const [listData2, setListData2] = useState([])
    // 分类的数据
    const [typeData2,setTypeData2] = useState([])

    useEffect(async () => {  
        const projectData = await http.get('/goods/getItemList',{
            type_id:0
        })
        if(projectData.code == 0){  
            setTypeData(projectData.typedata)
            setListData(projectData.listdata)
        }else{
            Toast.fail(projectData.msg)
        } 

        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : [] 
        setCartLocalData(localData)

        let localDataID = localStorage.getItem('billingCartDataID') ? JSON.parse(localStorage.getItem('billingCartDataID')): []
        setCartLocalDataID(localDataID)

    }, [])

    // 项目的请求接口
    const getDataFunc = async (typeId, tabsState = tabsStatus)=> {
        if(tabsState == '1'){
            setTypeData2([])
            const projectData = await http.get('/goods/getItemList',{
                type_id: typeId
            })
            if(projectData.code == 0){   
                setTypeData(projectData.typedata)
                setListData(projectData.listdata)
            }else{
                Toast.fail(projectData.msg)
            }
        }else if(tabsState == '2'){ 
            setTypeData2([])
            const projectData = await http.get('/goods/getProductList',{
                type_id: typeId
            })
            if(projectData.code == 0){  
                setTypeData(projectData.typedata)
                setListData(projectData.listdata)
            }else{
                Toast.fail(projectData.msg)
            }
        }else if(tabsState == '3'){ 
            setTypeData([])
            setListData([])
            setTypeData2([])
            // 套餐跟活动的格式跟项目产品的格式不一样，分开写
            const projectData = await http.get('/goods/getPackageInfo')
            if(projectData.code == 0){  
                setTypeData2(projectData.data)
            }else{
                Toast.fail(projectData.msg)
            }

        }else if(tabsState == '4'){ 
            setTypeData([])
            setListData([])
            setTypeData2([])
            setListData2([])
            // 套餐跟活动的格式跟项目产品的格式不一样，分开写
            const projectData = await http.get('/goods/getActivityClasssify')
            if(projectData.code == 0){  
                setTypeData2(projectData.data)
            }else{
                Toast.fail(projectData.msg)
            }

        }
        
    }

    // 点击套餐和活动的请求接口
    const getDataFunc2 = async(typeId) => {
        setTypeData2([])
        setListData2([])
        const projectData = await http.get('/goods/getActivityList',{
            activity_id: typeId
        })
        if(projectData.code == 0){    
            setListData2(projectData.data)
        }else{
            Toast.fail(projectData.msg)
        }
    }
 
    // 右边弹框
    const onOpenChange = () => {
        setModuleShow(!moduleShow) 
        // 弹框关闭的时候 恢复body 滚动条
        if (moduleShow == true) {
            //添加事件监听时添加了passive参数，在ios9中移除事件监听也需要加此参数
            document.body.removeEventListener('touchmove', window.scroll, { passive: true });
            document.body.style.overflow = 'auto';
        }
    } 
    // 点击已选择的项目 跳出弹框 
    const cartListClick = () => {
        setModuleShow(true)
        document.body.addEventListener("touchmove", window.scroll, { passive: false });
        document.body.style.overflow = 'hidden';
    }
    // 点击标签
    const typelistClick = (item) => {
        console.log(item)
        if(tabsStatus == '4'){
            item.name = item.activity_name
            getDataFunc2(item.tb_activity_id) 
        }else{
            // 请求 
            getDataFunc(item.id)
            
        }
        
        // let newData = labelData.slice(0, -1) 
        // setLabelData([...newData, item,{ name: '请选择' }])

        let newData = labelData
        setLabelData([...newData, item])
        
        
    }
    // 点击label 的时候
    const removeLabel = (item, idx) => {
        // if(tabsStatus == '4'){ 
        //     if(item.tb_activity_id!=undefined){ 
        //         let removeLabel = labelData.slice(0,idx+1)
        //         setLabelData([...removeLabel])
        //         getDataFunc(item.tb_activity_id)    
        //     }
        // }else{
        //     if(item.id!=undefined){
        //         let removeLabel = labelData.slice(0,idx+1)
        //         setLabelData([...removeLabel])
        //         getDataFunc(item.id)    
        //     }

        // }

        if(item.tb_activity_id!=undefined){ 
            let removeLabel = labelData.slice(0,idx+1)
            setLabelData([...removeLabel])
            getDataFunc2(item.tb_activity_id)    
        }else if(item.id!=undefined){
            let removeLabel = labelData.slice(0,idx+1)
            setLabelData([...removeLabel])
            getDataFunc(item.id)    
        }


        console.log(item)
        
 
        
    }
    // 点击tabs 
    const tabsClick = (val) => {
        console.log(val)
        setTabsStatus(val.value)
        getDataFunc(0, val.value)
         
        switch(val.value){
            case "1": return setLabelData([{ name: '项目',id:0 }]); break;
            case "2": return setLabelData([{ name: '产品',id:0 }]); break;
            case "3": return setLabelData([{ name: '套餐',id:0 }]); break;
            case "4": return setLabelData([{ name: '活动',id:0 }]); break;
        }

        
    }

    // 点击项目
    const projectClickCard = (e,item) => {
        e.stopPropagation() 
        item.strpperCount = 1
        item.itemType = tabsStatus
         
        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []  
        if(localData.length > 0){
            let findItem = localData.find((elem,index)=>{
                return elem.id == item.id
            })
            if(findItem == undefined){
                localData.push(item) 
            }else{
                // 重复点击的时候 移除当前数据
                let saveLocalData = localData
                localData = saveLocalData.filter(items => {
                    return items.id != item.id
                })
            }
        }else{
            localData.push(item) 
        } 
        localStorage.setItem('billingCartData',JSON.stringify(localData)) 
        setCartLocalData(localData)

        // 存一下 id 进行判断
        let localDataID = []
        localData.map(item => {
            localDataID.push(item.id)
        })
        localStorage.setItem('billingCartDataID',JSON.stringify(localDataID))
        setCartLocalDataID(localDataID)

    }
    // 重置购物车
    const allRemoveCart = () => {
        Modal.alert('提示', '是否确认重置购物车', [
            { text: '取消' },
            {
              text: '确认', onPress: async () => {
                localStorage.removeItem('billingCartData')
                localStorage.removeItem('billingCartDataID')
                setCartLocalData([])
                setCartLocalDataID([])
                setModuleShow(false)
                
              }
            }
        ]) 
    }
    // 购物车移除单条数据
    const oneRemoveCart = (data) => {
        let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
        let newLocalData = localData.filter(item => {
            return item.id != data.id
        })
        localStorage.setItem('billingCartData',JSON.stringify(newLocalData))
        setCartLocalData(newLocalData)

        // 重新赋值暂存id
        let localDataID = []
        newLocalData.map(item => {
            localDataID.push(item.id)
        })
        localStorage.setItem('billingCartDataID',JSON.stringify(localDataID))
        setCartLocalDataID(localDataID) 


        if(newLocalData.length < 1){
            setModuleShow(false)
        }
    }

    // 购物车增加数量跟减少数量
    const stepperCartChange = (e,data) => {
        console.log(data)
        console.log(e)
        if(e>10){
            e = 10
        }
        if(e<=10 && e>=0){
            let localData = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
            localData.map(item => {
                if(item.id == data.id){
                    item.strpperCount = e
                }
            })
            localStorage.setItem('billingCartData',JSON.stringify(localData))
            setCartLocalData(localData)
        } else if(e == 0){
            oneRemoveCart(data)
        }
    }
    // 搜索菜单
    const searchClick = (v) => {
        console.log(v)
        let searchVal = v.replace(/\s*/g,"")
        console.log(searchVal)
        if(searchVal != ''){
            history.push('/billing/search',{
                searchVal:searchVal
            })
        }else{
            Toast.fail("请输入要查找的项目")
        }
        
    }

    // 去开单
    const onSubmitGo = () => {
        console.log('111')
        history.push('/billingPage')
        setModuleShow(false)
        document.body.removeEventListener('touchmove', window.scroll, { passive: true });
        document.body.style.overflow = 'auto';
    }
    return (
        <div className="v-billing-project">
            <SearchBar placeholder="请输入要搜索的内容" ref={ref => { setSearchVal(ref) }} onSubmit={(v) => searchClick(v)}/>

            <div className="tabs">
                <Tabs tabs={tabs} onTabClick={(v) => tabsClick(v)} renderTabBar={props => <Tabs.DefaultTabBar {...props} page={4} />}>
                </Tabs>
                <div><WingBlank className="project-nav-title">已选择</WingBlank></div>
                <div className="project-click-list">
                    <ul>
                        {labelData.map((item, index) => (
                            <li onClick={() => removeLabel(item, index)}><span>{item.name}</span></li>
                        ))}
                    </ul>
                </div>
                <div><WingBlank className="project-nav-title">选择开单项目</WingBlank></div> 
                <div className="project-content">
                    {tabsStatus == '1' || tabsStatus == '2'?
                        <ul>
                            {/* 项目跟产品 */}
                            {typeData.map((item,index) => (
                                <li onClick={() => typelistClick(item)}><b>{index+1}</b><p>{item.name}</p><span className="iconfont icon-youjiantou1"></span></li>
                            ))}  
                            
                        </ul>
                    :''}
                    {tabsStatus == '3'? 
                        <div className="package-list-box">
                            {/* 套餐 */}
                            {typeData2.map((item,index) => (
                                 
                                <Accordion className={cartLocalDataID.includes(item.id)?'my-accordion-avtive':'my-accordion'} >
                                    <Accordion.Panel header={
                                        <div className="small-box">
                                            <div className="header">
                                                <b>{index+1}</b><p>{item.name}</p>
                                            </div>
                                            <div className="center">
                                                <span>价格:{item.price}</span>
                                                <p>{item.begin_date} ~ {item.end_date}</p>
                                                {cartLocalDataID.includes(item.id)?'':<span className="iconfont icon-zengjia" onClick={(e) => projectClickCard(e,item)}></span>}
                                            </div>
                                            {cartLocalDataID.includes(item.id)?
                                                <span className="sanjiaoxing" onClick={(e) => projectClickCard(e,item)}>
                                                    <span className="iconfont icon-dagou"></span>
                                            </span>:''} 
                                        </div>
                                    }> 
                                        <ul className="package-list-box-ul">
                                            {item.subdata.map((data,index) => (
                                                <li>
                                                    <div className="header-title">
                                                        {data.type_name}名称:{data.item_name}
                                                    </div>
                                                    
                                                    <div className="content">
                                                        <span className="color-style"></span>
                                                        <p>{data.dgname}</p> 
                                                        <p>原价:{data.original_price}元</p>
                                                        {data.type == '1'?<p>次数:{data.use_times?data.use_times:0}次</p>
                                                        :<p>{data.unit}{data.spec}</p>}
                                                        
                                                    </div>
                                                    <div className="footer">套餐价:{data.amt}元</div> 
                                                </li>
                                            ))}
                                        </ul>

                                    </Accordion.Panel>
                                    
                                </Accordion>
                                 
                            ))}
                        </div> 
                    :''}

                    {tabsStatus == '4'?
                        <ul>
                            {/* 套餐跟活动 */}
                            {typeData2.map((item,index)=>(
                                <li onClick={() => typelistClick(item)} className="box-package">
                                    <div className="package-header-box"> 
                                        <p>{item.activity_name}</p>
                                        <span className="iconfont icon-youjiantou1"></span>
                                    </div> 
                                    <div className="package-footer-box">
                                        <p>{item.begin_date} ~ {item.end_date}</p>
                                    </div>
                                </li>
                            ))} 
                        </ul>
                    :''}

                    
                    <div className="project-content-list">
                        {tabsStatus == '1'?
                            <ul> 
                                {/* 项目跟产品 */}
                                {listData.map((item,index)=> (
                                    <li onClick={(e) => projectClickCard(e,item)} className={cartLocalDataID.includes(item.id)?'project-list-active':''}>
                                        <div className="header-title">
                                            {item.name}
                                        </div>
                                        
                                        <div className="content">
                                            <span className="color-style"></span>
                                            <p>{item.type_name}</p> 
                                            <p>原价:{item.price}元</p>
                                            <p>次数:{item.use_times?item.use_times:0}次</p>
                                            {cartLocalDataID.includes(item.id)?'':<i className="iconfont icon-zengjia"></i>} 
                                        </div>
                                        <div className="footer">红线价格:{item.min_price}元</div>
                                        {cartLocalDataID.includes(item.id)?
                                            <span className="sanjiaoxing">
                                                <i className="iconfont icon-dagou"></i>
                                        </span>:''} 
                                    </li>
                                ))}  
                            </ul>
                        :''}
                        {tabsStatus == '2'?
                            <ul> 
                                {/* 项目跟产品 */}
                                {listData.map((item,index)=> (
                                    <li onClick={(e) => projectClickCard(e,item)} className={cartLocalDataID.includes(item.id)?'project-list-active':''}>
                                        <div className="header-title">
                                            {item.name}
                                        </div>
                                        
                                        <div className="content">
                                            <span className="color-style"></span>
                                            <p>{item.type_name}</p> 
                                            <p>{item.spec}/{item.basic_unit}</p> 
                                            {cartLocalDataID.includes(item.id)?'':<i className="iconfont icon-zengjia"></i>} 
                                        </div>
                                        <div className="footer">价格:{item.price}元</div>
                                        {cartLocalDataID.includes(item.id)?
                                            <span className="sanjiaoxing">
                                                <i className="iconfont icon-dagou"></i>
                                        </span>:''} 
                                    </li>
                                ))} 
                                
                                
                                
                            </ul>
                        :''}

                        {tabsStatus == '4'?
                            <ul> 
                                {/* 活动 */}
                                {listData2.map((item,index)=> (
                                    <li onClick={(e) => projectClickCard(e,item)} className={cartLocalDataID.includes(item.id)?'project-list-active':''}>
                                        <div className="header-title">
                                            {item.type_name}名称:{item.name}
                                        </div>
                                        
                                        <div className="content">
                                            <span className="color-style"></span>
                                            <p>{item.dgname}</p> 
                                            <p>原价:{item.original_price}元</p>
                                            {item.type == '1'?<p>次数:{item.use_times?item.use_times:0}次</p>
                                            :<p>{item.unit}{item.spec}</p>}
                                            {cartLocalDataID.includes(item.id)?'':<i className="iconfont icon-zengjia"></i>} 
                                        </div>
                                        <div className="footer">活动价:{item.activity_price}元</div> 
                                        {cartLocalDataID.includes(item.id)?
                                            <span className="sanjiaoxing">
                                                <i className="iconfont icon-dagou"></i>
                                        </span>:''} 
                                         
                                       
                                    </li>
                                ))} 
                                
                                
                                
                            </ul>
                        :''}
                        
                    </div>

                    <span className="no-data">无更多数据</span>
                </div>
            </div>

            <div className={cartLocalData.length > 0? 'project-shop-cart':'project-shop-cart cart-box-no-data'}>
                <div className="left" onClick={() => cartLocalData.length > 0?cartListClick():''}>
                    <span className="iconfont icon-wodedingdan2"></span>
                    <div className="left-sign">
                        <p>{cartLocalData.length}</p>
                    </div>
                </div>
                <div className="center" onClick={() => cartLocalData.length > 0?cartListClick():''}>
                    <p>已选择 {cartLocalData.length} 个开单项目</p>
                </div>
                <div className="right" onClick={() => onSubmitGo()}>
                    <p>去开单</p>
                </div>
            </div>
            

            {moduleShow? <Drawer
                className="my-drawer"
                style={{ position: 'fixed' }}
                position='bottom'
                enableDragHandle
                contentStyle={{ color: '#A6A6A6', textAlign: 'center', paddingTop: 42 }}
                sidebar={
                    <div className="project-drawer-box">
                        <div className="box-header"> 
                            <p>已经选择的开单项目</p>
                            <span onClick={() => allRemoveCart()}>重置</span>
                        </div>
                        <div className="box-content">
                            <ul>
                                {cartLocalData.map((item,index) => (
                                    <li>
                                        <p>
                                            {item.itemType == '1'?<b style={{color:'#2b4490'}}>[项目]</b>:(item.itemType == '2'?<b style={{color:'#007d65'}}>[产品]</b>:(item.itemType == '3'?<b style={{color:'#f47920'}}>[套餐]</b>:<b style={{color:'#e73746'}}>[活动]</b>))}
                                              &nbsp;{item.name}
                                        </p>
                                        <Stepper
                                            style={{ width: '80px',marginLeft:'20px',marginRight:'15px'}}
                                            showNumber
                                            max={10}
                                            min={1}
                                            value={item.strpperCount}
                                            onChange={(e) => stepperCartChange(e,item)}
                                        />
                                        <span className='iconfont icon-cuo' onClick={() => oneRemoveCart(item)}></span>
                                         
                                            
                                    </li>
                                ))} 
                            </ul>
                        </div>
                    </div> 
                }
                open={moduleShow}
                onOpenChange={() => onOpenChange()}
            >
            </Drawer>: ''}

            <Header />
            
        </div>
    )
}
export default BillingProject;